package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders.condition;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import net.valerijtimakov.homefinances.domain.common.CheckedData;
import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;
import net.valerijtimakov.homefinances.utils.Utils;

public class ListCondBuilder<T> extends CheckedData {
	
	private String fieldName;
	private Set<T> fieldValues = new HashSet<T>();
	
	public ListCondBuilder() {
		super();
	}
	
	public ListCondBuilder(String fieldName) {
		this();
		this.fieldName = fieldName;
	}

	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = checkNull(fieldName);
	}
	
	public void addFieldValue(T value) {
		fieldValues.add(value);
	}
	
	public void importFieldValues(Collection<T> values) {
		fieldValues.addAll(values);
	}
	
	public void importFieldValues(T[] values) {
		for (T value : values) {
			fieldValues.add(value);
		}
	}
	
	public void addCondition(StringBuilder condition) throws AppExceptionWrongState {
		if (fieldName.isEmpty() && fieldValues.size() > 0) {
			throw new AppExceptionWrongState("Не задано имя поля!");
		}
		if (fieldValues.size() > 0) {
			if (condition.length() > 0) {
				condition.append(" AND ");
			}
			condition.append("`");
			condition.append(fieldName);
			if (fieldValues.size() > 1) {
				condition.append("` IN (");
				Utils.implode(",", condition, fieldValues);
				condition.append(") ");
			} else {
				condition.append("` = ");
				condition.append(fieldValues.iterator().next());
			}
		}
	}
}
